<?php

namespace app\index\controller;

use app\index\model\Gallery;

/**
 * Class Image
 * @package app\index\controller
 */
class Image extends Base
{
    /**
     * 上传图片
     */
    public function upload($id)
    {
        $gallery = Gallery::get($id);
        if (!$gallery) {
            $this->error('图库不存在！');
        }
        if ($gallery->user_id != session('user.id')) {
            $this->error('无权操作此图库！');
        }
        // 图片上传
        $file = request()->file('image');
        $info = null;
        if ($file) {
            // 验证文件大小与后缀名
            $info = $file
                ->validate(['size' => 627120, 'ext' => 'jpg,png'])
                ->move(ROOT_PATH . 'public' . DS . 'uploads');
            if (!$info) {
                $this->error('图片上传失败：' . $file->getError());
            }
        } else {
            $this->error('图片不能为空！');
        }
        // 获取传入参数
        $data = getInputData(['name']);
        // 验证传入参数
        $verify = validateData($data, 'image', 'upload');
        if ($verify === true) {
            $image = new \app\index\model\Image();
            $image->name = $data['name'];
            $image->path = $info->getSaveName();
            $image->gallery_id = $id;
            $image->save();
            $this->success('新增成功！', url('mine/show', ['id' => $id]));
        } else {
            $this->error('新增失败：' . $verify);
        }
    }

    /**
     * 修改图片页面
     */
    public function edit($id)
    {
        $image = \app\index\model\Image::get($id);
        if (!$image) {
            $this->error('图片不存在！');
        }
        $gallery = Gallery::get($image->gallery_id);
        if ($gallery->user_id != session('user.id')) {
            $this->error('无权操作此图片！');
        }
        $this->assign('image', $image);
        $this->assign('gallery', $gallery);
        return view();
    }

    /**
     * 修改图片
     */
    public function update($id)
    {
        $data = getInputData(['name']);
        $image = \app\index\model\Image::get($id);
        if (!$image) {
            $this->error('图片不存在！');
        }
        $gallery = Gallery::get($image->gallery_id);
        if ($gallery->user_id != session('user.id')) {
            $this->error('无权操作此图片！');
        }
        if (!empty($data['name'])) {
            $image->name = $data['name'];
        }
        $image->save();
        $this->success('修改成功！', url('mine/show', ['id' => $image->gallery_id]));
    }

    /**
     * 删除图片
     */
    public function delete($id)
    {
        $image = \app\index\model\Image::get($id);
        if (!$image) {
            $this->error('图片不存在！');
        }
        $gallery = Gallery::get($image->gallery_id);
        if ($gallery->user_id != session('user.id')) {
            $this->error('无权操作此图片！');
        }
        $image->delete();
        $this->success('删除成功！', url('mine/show', ['id' => $image->gallery_id]));
    }
}
